const wxMini = (callBackFn) => {
	$(function() {
		$('[minUrl^="wxMiniprogram://"]').each(function(index, element) {
			var ahref = $(this).attr('minUrl'),
				el = $(this);
			$(this).css({
				'display': 'block',
				'position': 'relative',
			});
			let device = navigator.userAgent;
			var isWeixin = device.toLowerCase().indexOf('micromessenger') != -1;
			var wx_stringArr = isWeixin ? device.toLowerCase().match(/micromessenger\/([\d\.]+)/i) :
				0;
			var wx_version = wx_stringArr.length > 0 ? device.toLowerCase().match(
				/micromessenger\/([\d\.]+)/i)[
				1] : 0; //微信版本号
			var wx_for = isWeixin ? (wx_version.split('.')[0] >= 7 || (wx_version.split('.')[1] >=
				0 &&
				wx_version.split('.')[0] == 7) || (wx_version.split('.')[2] >= 12 &&
				wx_version.split(
					'.')[0] == 7 && wx_version.split('.')[1] == 0)) : 0; //微信版本号是否大于7.0.12
			ahref = ahref.replace('wxMiniprogram://', "");
			let idInfo = ahref.split('?/')[0];
			let miniId = idInfo.split('/')[1]; //appid
			let path = ahref.split('?/')[1];
			path = path != undefined && path ? '/' + path : '';
			if (isWeixin && wx_for && window.__wxjs_environment != 'miniprogram') {
				wxOpentag(el, miniId, path);
			}
		});

		function wxOpentag(el, id, path) {
			setTimeout(function() {
				let aw = (el.width() == 0) ? 120 : el.width(),
					ah = (el.height() == 0) ? 120 : el.height();
				if (path && path.indexOf('huoniao/') > -1) {
					path = path.replace('huoniao/', '/pages/redirect/index?url=/');
				}
				let h5ToweappCss = 'display:block;position:absolute;top:0;right:0;left:0;bottom:0;'
				let html =
					`<div class="h5Toweapp" id="h5Toweapp" style="${h5ToweappCss}">
		                <wx-open-launch-weapp id="launch-weapp-btn" appid="${id}" path="${path}" style="display:block">
		                    <template>\n
		                        <style>.toH5Btn { diplay:block; width:100%; height:100%; line-height:${ah}px; opacity:0; background:#f00; font-size:16px; color:#000;</style>\n
		                        <a href="javascript:;" class="toH5Btn">立即打开</a>\n
		                    </template>\n
		                </wx-open-launch-weapp>\n
		            </div>`;
				el.append(html);
				jWeixin.ready(function() {
					let btn = document.getElementById('launch-weapp-btn');
					if (btn) {
						btn.addEventListener('launch', function(e) {
							callBackFn.success && (callBackFn.success()); //打开成功的回调
						});
						btn.addEventListener('error', function(e) {
							callBackFn.fail && (callBackFn.fail()); //打开失败的回调
							console.log('fail', e.detail);
						});
					}
				})
			}, 300);
		}
	})
}
export default wxMini;